<template>
    <a-tree-select
        v-bind="$attrs"
        :disabled="disabled"
        v-model="currentValue"
        :treeData="treeData"
        :replaceFields="{ children: 'children', title: 'label', key: 'id',value:'id' }"
        :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
        placeholder="请选择"
        @select="onSelect">
        <a-icon v-if="loading" style="color: #096dd9" slot="suffixIcon" type="loading" />
        <a-spin v-if="loading" slot="notFoundContent" size="small" />
    </a-tree-select>

</template>

<script>
import { getCustOrgTree } from '@/api/subassembly/TreeSelectOrganization'

/*
* 示例
* 表单：
注：只要选中条目的id，可以不监听onSelectChange事件
<SelectCompanyAndProject
    disabled
    :auto-select="true"
    v-model="formData.depId"
    @onSelectChange="formData.depName = $event.name">
</SelectCompanyAndProject>

搜索框：
{
    name: '单位',
    valueKey: 'depId',
    type: SelectCompanyAndProject
},
*
*说明：
* 自动判断当前岗位，
* 如果是PD，则手动生成一条数据
* 如果是CO，则显示所有数据
* 如果是BC，则循环所有数据，匹配到对应的数据，然后单独取出来放到treeData里面
*
* onSelectChange事件：
* 数据改变时会发射onSelectChange事件，$event为{ id , name} , 根据需要自己取 ，name值是上级加上本级的名字，如: 四川分公司 - 综合管理部 ，
* id是选中条目的id
*
* */
export default {
    // v-model绑定的数据
    props: {
        value: {
            type: [Array, String, Object]
        },
        autoSelect: {
            type: Boolean,
            default: false
        },
        disabled: {
            type: Boolean,
            default: false
        },
        //是否根据用户权限筛选数据
        isAuth: {
            type: Boolean,
            default: true
        },
        //是否自动选中我
        isAutoSelectMe: {
            type: Boolean,
            default: false
        },
        // 请求的额外参数
        extraParams: {
            type: Object,
            default: ()=> ({})
        },
        // 是否禁用父级，只启用末级
        parentDisabled: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            treeData: [],
            loading: false
        }
    },
    created() {
        this.getCompanyList()
    },
    methods: {
        /**
         * @description: 扁平化数据
         * @param {array} data
         * @return {void}
         */
        flatTree(tree) {
            for (let i = 0; i < tree.length; i++) {
                const node = tree[i]
                if (node.children) {
                    // 禁用父级节点
                    node.disabled = true
                    this.flatTree(node.children)
                }
            }
        },
        onSelect(e, node) {
            // console.log(e, node)
            let parent = node.$parent.$vnode.data.props
            let child = node.$vnode.data.props
            let name = ''
            let code // 组织code
            let codeName // 组织code名称
            let tag = child.data.tag // 组织标签
            // 根据标签获取当前选项的组织code
            if (tag.includes('CO')) {
                code = 'CO'
                codeName = '公司'
            } else if (tag.includes('BC')) {
                code = 'BC'
                codeName = '分公司'
            } else if (tag.includes('PD')) {
                code = 'PD'
                codeName = '项目'
                if (parent.id) {
                    name = parent.title + ' - '
                }
            }
            name = name + child.title
            this.$emit('onSelectChange', { id: e, name, code, codeName })
            code && this.$emit('update:orgCode', code)
            codeName && this.$emit('update:orgCodeName', codeName)
        },
        async getCompanyList() {
            let params = Object.assign({},{
                containTags:['CO','BC','PD'],
                baseOrgType:0, 
                systemOrgType: 1, 
                containVirtual: 1, 
            },this.extraParams)
            this.loading = true
            let res = await getCustOrgTree(params)
            this.loading = false
            this.parentDisabled && this.flatTree(res.data)
            if (this.isAuth){
                //如果用户岗位是项目部的
                if (this.$userType() === 'PD') {
                    // if (false) {
                    this.treeData = [
                        {
                            'id': this.$currentPost().id,
                            'label': this.$currentPost().orgName + ' - ' + this.$currentPost().name,
                            children: [],
                            data: { tag: ['PD'] }
                        }
                    ]
                    if (this.autoSelect) {
                        this.currentValue = this.treeData[0].id
                        this.$emit('onSelectChange', {
                            id: this.treeData[0].id,
                            name: this.treeData[0].label,
                            parentId: this.$currentPost().orgId,
                            parentName: this.$currentPost().orgName
                        })
                    }
                    return
                }
                //如果用户岗位是分公司
                if (this.$userType() === 'BC') {
                    this.recursion(res.data, null)
                } else {
                    this.treeData = res.data
                    if (this.autoSelect) {
                        this.currentValue = this.treeData[0].id
                        this.$emit('onSelectChange', {
                            id: this.treeData[0].id,
                            name: this.treeData[0].label
                        })
                    }
                }
            }else {
                this.treeData = res.data

                if (this.autoSelect) {
                    this.currentValue = this.treeData[0].id
                    this.$emit('onSelectChange', {
                        id: this.treeData[0].id,
                        name: this.treeData[0].label
                    })
                }
                if (this.isAutoSelectMe) {
                    this.currentValue = this.$currentPost().id
                    this.$emit('onSelectChange', {
                        id: this.$currentPost().id,
                        name: this.$currentPost().name
                    })
                }
            }

        },
        recursion(items, parent) {
            for (let i = 0; i < items.length; i++) {
                let item = items[i]
                if (item.id === this.$currentPost().id) {
                    this.treeData = [item]
                    if (this.autoSelect) {
                        this.currentValue = this.treeData[0].id
                        this.$emit('onSelectChange', {
                            id: this.treeData[0].id,
                            // name: parent.label + '-' + item.label
                            name: item.label
                        })
                    }
                } else {
                    if (item.children) {
                        this.recursion(item.children, item)
                    }
                }
            }
        }
    },
    computed: {
        // 转换绑定的选中数据，与v-model同步
        currentValue: {
            get: function() {
                return this.value
            },
            set: function(value) {
                // console.log(value)
                this.$emit('input', value)
                this.$emit('change', value)
            }
        }
    }
}
</script>
